/*******************************************************************************
 * Copyright 2011-2013 Sergey Tarasevich
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package com.tdzx.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKEvent;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKGeocoderAddressComponent;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.MemoryCacheAware;
import com.nostra13.universalimageloader.cache.memory.impl.LRULimitedMemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.tdzx.constant.Constant;
import com.tdzx.entity.Area;
import com.tdzx.entity.KuanterService;
import com.tdzx.entity.Member;
import com.tdzx.entity.TDService;
import com.tdzx.entity.Type;
import com.tdzx.mail.CrashHandler;
import com.tdzx.util.SharePrefenceUtil;

/**
 * @author Utopia
 */
public class UILApplication extends Application {
	 public LocationData locData = null;	//当前定位位置
	 public static final String strKey = "A4A564A5671A62E5C30E43C267C6FCC04B3213BE"; //百度地图key  陶都在线
	 public BMapManager mBMapManager = null;
	 LocationClientOption option;
	//定位
	public LocationClient mLocationClient = null;
	public MyLocationListenner myListener = new MyLocationListenner();
	MKSearch mSearch;
	public boolean m_bKeyRight = true;
	
	public static String currenrCityName = "";
	public static int location_cuccess = 0;
	public static int location_fial = -200;
	
	public static String DEFAULT_SORT = "距离最近";		//默认排序标志，根据这个参数来显示列表
	
	public static UILApplication application;
	
	private List<Type> list_type = new ArrayList<Type>();  //种类
	private List<TDService> list_service = new ArrayList<TDService>();	//服务
	private List<Area> list_area = new ArrayList<Area>();  //地区
	
	private Member member;
	
	public Member getMember() {
		return member;
	}

	public void setMember(Member member) {
		this.member = member;
	}

	public List<Area> getList_area() {
		return list_area;
	}

	public void setList_area(List<Area> list_area) {
		this.list_area = list_area;
	}

	public List<Type> getList_type() {
		return list_type;
	}

	public void setList_type(List<Type> list_type) {
		this.list_type = list_type;
	}

	public List<TDService> getList_service() {
		return list_service;
	}

	public void setList_service(List<TDService> list_service) {
		this.list_service = list_service;
	}

	@SuppressWarnings("unused")
	@Override
	public void onCreate() {
		if (Config.DEVELOPER_MODE && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyDialog().build());
			StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyDeath().build());
		}

		super.onCreate();

		initImageLoader(getApplicationContext());
		
		initEngineManager(this);	//初始化地图引擎
		mLocationClient = new LocationClient(getApplicationContext());
		mLocationClient.registerLocationListener(myListener);	//注册定位监听
		option = new LocationClientOption();
		option.setOpenGps(true);
		option.setCoorType("bd09ll");
		option.setAddrType("all");
		option.setScanSpan(60 * 60 * 1000);  //大于0表示这个时间间隔请求一次定位
		option.disableCache(true);  //启用缓存
		
		mLocationClient.setLocOption(option);
		mLocationClient.start();
		
		//捕获异常处理
		CrashHandler crashHandler = CrashHandler.getInstance();    
//        crashHandler.init(getApplicationContext());   
		
		mSearch = new MKSearch();
		mSearch.init(mBMapManager, new MKSearchListener() {
			
			@Override
			public void onGetWalkingRouteResult(MKWalkingRouteResult arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onGetTransitRouteResult(MKTransitRouteResult arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onGetPoiDetailSearchResult(int arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onGetDrivingRouteResult(MKDrivingRouteResult arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onGetAddrResult(MKAddrInfo res, int error) {
				// TODO Auto-generated method stub
				if (error != 0) {
					String str = String.format("错误号：%d", error);
					Toast.makeText(UILApplication.this, "地图查找失败",
							Toast.LENGTH_LONG).show();
					return;
				}
				
				if (res.type == MKAddrInfo.MK_REVERSEGEOCODE){
					currenrCityName = res.strAddr;
					
//					currenrCityName = mac.city;
					Log.i("aaa", currenrCityName + "---fanjiema");
					if(mHandler != null) {
						Message message = mHandler.obtainMessage();
						message.obj = currenrCityName;
						if(!currenrCityName.equals("")) {
							message.what = location_cuccess;
						} else {
							message.what = location_fial;
						}
	                	mHandler.sendMessage(message);
	                }
				}
				/*MKGeocoderAddressComponent mac = res.addressComponents;
				if (mac != null) { //
					currenrCityName = mac.city;
					Log.i("aaa", currenrCityName);
					if(mHandler != null) {
						Message message = mHandler.obtainMessage();
						message.obj = currenrCityName;
						if(!currenrCityName.equals("")) {
							message.what = location_cuccess;
						} else {
							message.what = location_fial;
						}
	                	mHandler.sendMessage(message);
	                }
				}*/
				
				
			}
		});
		super.onCreate();
	}
	
	public UILApplication() {
		application = this;
		 
	}

	public static void initImageLoader(Context context) {
		int memoryCacheSize = (int) (Runtime.getRuntime().maxMemory() / 8);

		MemoryCacheAware<String, Bitmap> memoryCache;
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
			memoryCache = new LruMemoryCache(memoryCacheSize);
		} else {
			memoryCache = new LRULimitedMemoryCache(memoryCacheSize);
		}

		// This configuration tuning is custom. You can tune every option, you may tune some of them, 
		// or you can create default configuration by
		//  ImageLoaderConfiguration.createDefault(this);
		// method.
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
				.threadPriority(Thread.NORM_PRIORITY - 2)
				.memoryCache(memoryCache)
				.denyCacheImageMultipleSizesInMemory()
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.enableLogging() // Not necessary in common
				.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
	}
	
	public static class Config {
		public static final boolean DEVELOPER_MODE = false;
	}
	
	public void initEngineManager(Context context) {
        if (mBMapManager == null) {
            mBMapManager = new BMapManager(context);
        }
        

        if (!mBMapManager.init(strKey,new MyGeneralListener())) {
            Toast.makeText(getApplicationContext(), 
                    "BMapManager  初始化错误!", Toast.LENGTH_LONG).show();
        }
	}
	
	// 定位监听
	public class MyLocationListenner implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;

			locData = new LocationData();
			locData.latitude = location.getLatitude();  //TODO
			locData.longitude = location.getLongitude();	//TODO
			locData.accuracy = location.getRadius();
			locData.direction = location.getDerect();
			
			GeoPoint gp = new GeoPoint((int)(location.getLatitude()*1E6), (int)(location.getLongitude()*1E6));
			if (location.getLocType() == BDLocation.TypeNetWorkLocation){
                String province = location.getProvince();
                String city = location.getCity();
                String district = location.getDistrict();
                String address = location.getAddrStr();
                currenrCityName = province + city + district + address;
                if(mHandler != null) {
					Message message = mHandler.obtainMessage();
					message.obj = currenrCityName;
					if(!currenrCityName.equals("")) {
						message.what = location_cuccess;
					} else {
						message.what = location_fial;
					}
                	mHandler.sendMessage(message);
                }
                
                Log.i("ccc", province + "!!--" + city + "--" + district + "--" + address);
//                Toast.makeText(UILApplication.this, province + "--" + city + "--" + district + "--" + address, Toast.LENGTH_SHORT).show();
            } else {
            	mSearch.reverseGeocode(gp);
            }
			
			if(!((locData.latitude + "").contains("4.9E")) || !((locData.longitude + "").contains("4.9E")) ){
//				mLocationClient.stop();
				if(SharePrefenceUtil.checkLogin(UILApplication.this)) {
					RequestParams params = new RequestParams();
					params.put("member_id", SharePrefenceUtil.getUserID(UILApplication.this));
					params.put("lat", locData.latitude + "");
					params.put("lon", locData.longitude + "");
					new AsyncHttpClient().post(Constant.insertUserLocation, params, new AsyncHttpResponseHandler() {
						@Override
						public void onSuccess(String content) {
							super.onSuccess(content);
						}
						@Override
						public void onFailure(Throwable error, String content) {
							super.onFailure(error, content);
						}
						
					});
				}
			} else {
				mLocationClient.requestLocation();
			}
		}

		@Override
		public void onReceivePoi(BDLocation arg0) {
			
		}
	}
	
	// 常用事件监听，用来处理通常的网络错误，授权验证错误等
    public static class MyGeneralListener implements MKGeneralListener {
        
        @Override
        public void onGetNetworkState(int iError) {
            if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
                Toast.makeText(application, "您的网络出错啦",
                    Toast.LENGTH_LONG).show();
            }
            else if (iError == MKEvent.ERROR_NETWORK_DATA) {
                Toast.makeText(application, "输入正确的检索条件",
                        Toast.LENGTH_LONG).show();
            }
            // ...
        }

        @Override
        public void onGetPermissionState(int iError) {
            if (iError ==  MKEvent.ERROR_PERMISSION_DENIED) {
                Toast.makeText(application, 
                        "权限不足", Toast.LENGTH_LONG).show();
                application.m_bKeyRight = false;
            }
        }
    }
    
    
    private Handler mHandler;	//定位后发送通知到请求定位的界面
    public void startRequest(Handler mHandler) {
		this.mHandler = mHandler;
		if(mLocationClient.isStarted()) {
			mLocationClient.requestLocation();
		} else {
			mLocationClient.start();
		}
	}
    
    private List<KuanterService> list_kuanterService;  //服务列表
    public List<KuanterService> getList_kuanterService() {
		return list_kuanterService;
	}

	public void setList_kuanterService(List<KuanterService> list_kuanterService) {
		this.list_kuanterService = list_kuanterService;
	}
	
}